package org.nnxy.foodboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.nnxy.foodboot.entity.Recipe;
import org.nnxy.foodboot.entity.UserViewHistory;
import org.nnxy.foodboot.mapper.UserViewHistoryMapper;
import org.nnxy.foodboot.service.PopularRecipeService;
import org.nnxy.foodboot.service.UserViewHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户浏览历史服务实现类
 */
@Service
public class UserViewHistoryServiceImpl extends ServiceImpl<UserViewHistoryMapper, UserViewHistory> implements UserViewHistoryService {

    @Autowired
    private UserViewHistoryMapper userViewHistoryMapper;
    
    @Autowired
    private PopularRecipeService popularRecipeService;
    
    /**
     * 记录用户浏览历史
     *
     * @param userId 用户ID
     * @param recipeId 食谱ID
     * @param viewDuration 浏览时长(秒)
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean recordViewHistory(Long userId, Long recipeId, Integer viewDuration) {
        if (userId == null || recipeId == null) {
            return false;
        }
        
        // 创建新的浏览记录
        UserViewHistory viewHistory = new UserViewHistory();
        viewHistory.setUserId(userId);
        viewHistory.setRecipeId(recipeId);
        viewHistory.setViewDuration(viewDuration);
        
        boolean result = this.save(viewHistory);
        
        // 更新热门食谱指标
        if (result) {
            popularRecipeService.updateRecipePopularityMetrics(recipeId, 1, 0, 0);
        }
        
        return result;
    }
    
    /**
     * 分页查询用户浏览历史
     *
     * @param page 分页参数
     * @param userId 用户ID
     * @return 分页结果
     */
    @Override
    public IPage<Recipe> pageUserViewHistory(Page<Recipe> page, Long userId) {
        return userViewHistoryMapper.selectUserViewHistoryRecipes(page, userId);
    }
    
    /**
     * 获取用户最近的浏览历史
     *
     * @param userId 用户ID
     * @param recipeId 食谱ID
     * @return 浏览历史
     */
    @Override
    public UserViewHistory getLatestViewHistory(Long userId, Long recipeId) {
        return userViewHistoryMapper.getUserLatestViewHistory(userId, recipeId);
    }
    
    /**
     * 清空用户浏览历史
     *
     * @param userId 用户ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean clearUserViewHistory(Long userId) {
        return this.remove(
                new LambdaQueryWrapper<UserViewHistory>()
                    .eq(UserViewHistory::getUserId, userId)
        );
    }
} 